package xyz.missou.blog.controller.manage;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import xyz.missou.blog.controller.BaseController;
import xyz.missou.blog.entity.Tag;
import xyz.missou.blog.service.TagService;

import javax.annotation.Resource;

@Controller
@RequestMapping("/manage/tag")
public class ManageTagController extends BaseController {

    @Resource
    private TagService tagService;

    @RequestMapping({"/add/","/add"})
    public String add(Model model, RedirectAttributes redirectAttributes, @RequestParam("name") String name, @RequestParam("summary") String summary){
        Tag tag=tagService.getTagByName(name);
        if (tag==null){
            tag=new Tag();
            tag.setName(name);
            tag.setSummary(summary);
            tagService.addTag(tag);
        }else {
            redirectAttributes.addAttribute("msg","该标签已存在，请更换名称后重新添加！");
        }
        return "redirect:/manage/tag/";
    }

    @RequestMapping({"/delete/{id}/","/delete/{id}"})
    public String delete(Model model, @PathVariable("id") Integer id){
        tagService.deleteTagById(id);
        return "redirect:/manage/tag/";
    }

    @RequestMapping({"/update/{id}/","/update/{id}"})
    public String update(Model model, RedirectAttributes redirectAttributes, @PathVariable("id") Integer id, @RequestParam("name") String name, @RequestParam("summary") String summary){
        Tag tag=tagService.getTagByName(name);
        if (tag==null || tag.getId()==id){
            tag=new Tag();
            tag.setId(id);
            tag.setName(name);
            tag.setSummary(summary);
            tagService.updateTag(tag);
        }else {
            redirectAttributes.addAttribute("msg","该分类名已存在，请更换后重新修改！");
        }
        return "redirect:/manage/tag/";
    }
}
